from cqssc.lottery import Lottery
from cqssc.db.mysql import Mysql
import pymysql


# 本期：进行中未开奖期
# 上期：于本期前一期，刚开完奖倒序第一期
# 生成购买计划
class ForecastBig:
    db = None
    location = 1
    table = "big_or_small"
    is_pass = False
    period = None
    pre_period = None
    period_number = None
    cardinality = 10
    data = {'period': '', 'number': '0', "location": "1", "location_number": "0", "is_big": 1, "pass": 0, "multiple": 1,
            "cardinality": 10, "win": 0, "money": 0}

    # 根据当前开奖期号计算前一期开奖期号
    def pre_period(self):
        day = 0
        pre_period = self.period_number - 1
        if pre_period <= 0:
            pre_period = 120
            day = -1

        pre_period = str(pre_period).zfill(3)
        return "{prefix}-{current_period}".format(prefix=self.lottery_period.getPeriodPrefix(day),
                                                  current_period=pre_period)

    # 根据当前开奖期号计算前一期开奖期号
    def next_period(self):
        day = 0
        next_period = int(self.period_number) + 1
        if next_period > 120:
            next_period = 1
            day = 1

        next_period = str(next_period).zfill(3)
        return "{prefix}-{current_period}".format(prefix=self.lottery_period.getPeriodPrefix(day),
                                                  current_period=next_period)

    # period,format: 170611-001
    def __init__(self, period, location=1, table=None):
        self.lottery_period = Lottery()
        self.db = Mysql()
        self.location = int(location)
        self.period = period
        periods = period.split("-")
        self.period_number = int(periods[1])

        if table is not None:
            self.table = table

        print("{period}:{location}".format(period=self.pre_period(), location=self.location))

    # 查找有没有已经存在的期数对应位置的预测
    def findForecastData(self, period):
        find_data_sql = r"select * from `{table}` where period=%s and location=%s".format(table=self.table)
        self.db.find_cursor = self.db.connection.cursor(pymysql.cursors.DictCursor)
        self.db.find_cursor.execute(find_data_sql, (period, self.location))
        result = self.db.find_cursor.fetchone()

        if result is None:
            return False
        else:
            return result

    # 计算数据并且生成下一期的购买计划（下一期=当前未开奖期）
    def forecast(self):
        self.data['period'] = self.next_period()
        self.data['location'] = self.location
        # 看看下一期是不是已经预测过，预测过就不再插入
        has_next_forecast = self.findForecastData(self.next_period())

        if has_next_forecast is False:
            self.forecast_current()
            sql_values = tuple(self.data.values())
            new_data_sql = r"insert into `{table}`(`period`,`number`,`location`,`location_number`,`is_big`,`pass`,`multiple`,`cardinality`," \
                           r"`win`,`money`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".format(table=self.table)
            sta = self.db.cursor.execute(new_data_sql, sql_values)
            self.db.connection.commit()
            self.db.cursor.close()
            self.db.connection.close()
            return sta

        return True

    # 计算下一期的购买计划数据
    def forecast_current(self):
        # 这里更改为查找当前开奖期数的预测记录，来生成下一期的数据，在此之前（BigOrSmall）会生成当前期数据或更新
        pre_data = self.findForecastData(self.period)

        if pre_data is False:
            # 如果没有上一期的购买记录，则分析上一期的开奖记录然后预测本期
            print("No Pre Data")
            return False
        else:
            pre_is_win = pre_data["win"]
            pre_is_big = pre_data["is_big"]
            pre_is_pass = pre_data["pass"]

            # 如果上局放弃同时也输了,本期购买数据继续继承上局购买数据，放弃购买
            if pre_is_pass == 1 and pre_is_win == 0:
                self.data['pass'] = 1
                self.data['is_big'] = pre_is_big
                self.data['multiple'] = pre_data['multiple']
                self.data['cardinality'] = pre_data['cardinality']
                self.data['money'] = pre_data['money']

            # 如果上期放弃但是中了，111121
            elif pre_is_pass == 1 and pre_is_win == 1:
                # 本期不放弃
                self.data['pass'] = 0
                # 本期购买上期的反向
                self.data['is_big'] = int(not pre_is_big)
                # 倍数：1
                self.data['multiple'] = 1
                # 基数10
                self.data['cardinality'] = self.cardinality
                self.data['money'] = self.data['multiple'] * self.data['cardinality']

            # 如果上期没有放弃，赢了，继续买反方向
            elif pre_is_pass == 0 and pre_is_win == 1:
                # 本期不放弃
                self.data['pass'] = 0
                # 本期购买上期的反向
                self.data['is_big'] = int(not pre_is_big)
                # 倍数：1
                self.data['multiple'] = 1
                # 基数 10
                self.data['cardinality'] = self.cardinality
                self.data['money'] = self.data['multiple'] * self.data['cardinality']

            # 如果上期没有放弃，输了，则加倍购买；
            # 这里有2种情况
            # 如果上期输了已经是加倍购买的，则开始放弃
            # 如果上期输了但是倍数为1，则加倍购买
            elif pre_is_pass == 0 and pre_is_win == 0:
                # 如果已经倍投，但是还没有中，则保存购买方向状态，本期放弃购买
                if pre_data['multiple'] == 2:
                    # 本期放弃
                    self.data['pass'] = 1
                    # 本期购买上期的同方向
                    self.data['is_big'] = pre_is_big
                    # 倍数：1
                    self.data['multiple'] = 1
                    # 基数10
                    self.data['cardinality'] = self.cardinality
                    self.data['money'] = self.data['multiple'] * self.data['multiple']

                elif pre_data['multiple'] == 1:
                    # 本期放弃
                    self.data['pass'] = 0
                    # 本期购买上期的同方向
                    self.data['is_big'] = pre_is_big
                    # 倍数：2
                    self.data['multiple'] = 2
                    # 基数10
                    self.data['cardinality'] = self.cardinality
                    self.data['money'] = self.data['multiple'] * self.data['cardinality']


if __name__ == "__main__":
    forecast = ForecastBig(period="170610-001", location=1)
    forecast.forecast()
